<template>
  <div class="order-manager">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics">
      <el-col :span="6" v-for="item in statisticsData" :key="item.title">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ item.value }}</div>
          <div class="stat-title">{{ item.title }}</div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 查询条件 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择订单状态"
            style="min-width: 140px"
          >
            <el-option label="待支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="已发货" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已关闭" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 订单列表 -->
    <el-table :data="orderList" stripe border v-loading="loading">
      <el-table-column prop="orderId" label="订单号" width="180" />
      <el-table-column prop="createTime" label="下单时间" width="180" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="productName" label="商品名称" />
      <el-table-column prop="amount" label="订单金额" width="100">
        <template #default="{ row }">
          ¥{{ row.amount }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getOrderStatusType(row.status)">
            {{ getOrderStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleViewDetail(row)"
          >
            查看详情
          </el-button>
          <el-button 
            v-if="row.status === 'paid'"
            type="success" 
            size="small" 
            @click="handleShip(row)"
          >
            发货
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 修改订单详情弹窗为抽屉组件 -->
    <el-drawer
      v-model="showDetailDrawer"
      title="订单详情"
      size="600px"
      :destroy-on-close="true"
    >
      <div class="order-detail-drawer" v-if="currentOrder">
        <!-- 订单状态进度 -->
        <div class="progress-section">
          <el-steps :active="getOrderProgress(currentOrder.status)" finish-status="success">
            <el-step title="提交订单" description="用户提交订单"></el-step>
            <el-step title="付款成功" description="等待商家发货"></el-step>
            <el-step title="商品发货" description="等待签收"></el-step>
            <el-step title="交易完成" description="订单已完成"></el-step>
          </el-steps>
        </div>

        <!-- 订单基本信息 -->
        <div class="detail-section">
          <div class="section-title">
            <i class="el-icon-document"></i>
            订单信息
          </div>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">订单编号：</span>
              <span class="value">{{ currentOrder.orderId }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ currentOrder.createTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单状态：</span>
              <el-tag :type="getOrderStatusType(currentOrder.status)">
                {{ getOrderStatusText(currentOrder.status) }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">支付方式：</span>
              <span class="value">{{ currentOrder.paymentMethod || '微信支付' }}</span>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="detail-section">
          <div class="section-title">
            <i class="el-icon-shopping-cart-full"></i>
            商品信息
          </div>
          <div class="product-card">
            <img :src="currentOrder.productImage" :alt="currentOrder.productName">
            <div class="product-info">
              <h4>{{ currentOrder.productName }}</h4>
              <div class="price">¥{{ currentOrder.amount }}</div>
            </div>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="detail-section">
          <div class="section-title">
            <i class="el-icon-location"></i>
            收货信息
          </div>
          <div class="address-card">
            <div class="contact">
              <span class="name">{{ currentOrder.address?.name }}</span>
              <span class="phone">{{ currentOrder.address?.phone }}</span>
            </div>
            <div class="address">{{ currentOrder.address?.fullAddress }}</div>
          </div>
        </div>

        <!-- 订单金额信息 -->
        <div class="detail-section">
          <div class="section-title">
            <i class="el-icon-money"></i>
            金额信息
          </div>
          <div class="amount-list">
            <div class="amount-item">
              <span>商品金额</span>
              <span>¥{{ currentOrder.amount }}</span>
            </div>
            <div class="amount-item">
              <span>运费</span>
              <span>¥{{ currentOrder.shippingFee || '0.00' }}</span>
            </div>
            <div class="amount-item">
              <span>优惠金额</span>
              <span class="discount">-¥{{ currentOrder.discount || '0.00' }}</span>
            </div>
            <div class="amount-item total">
              <span>实付金额</span>
              <span class="total-amount">¥{{ currentOrder.amount }}</span>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="drawer-footer">
          <el-button @click="showDetailDrawer = false">关闭</el-button>
          <el-button 
            v-if="currentOrder.status === 'paid'"
            type="primary" 
            @click="handleShip(currentOrder)"
          >
            发货
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟数据
const mockOrders = Array.from({ length: 100 }).map((_, index) => ({
  orderId: `ORDER${String(index + 1).padStart(6, '0')}`,
  createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString(),
  username: `user${index + 1}`,
  productName: `商品${index + 1}`,
  productImage: `https://picsum.photos/200/200?random=${index}`,
  amount: Math.floor(Math.random() * 1000) + 99,
  status: ['pending', 'paid', 'shipped', 'completed', 'cancelled'][Math.floor(Math.random() * 5)],
  address: {
    name: '张三',
    phone: '13800138000',
    fullAddress: '北京市朝阳区三里屯SOHO'
  }
}))

// 状态映射
const statusMap = {
  pending: { type: 'warning', text: '待付款' },
  paid: { type: 'success', text: '已付款' },
  shipped: { type: 'primary', text: '已发货' },
  completed: { type: '', text: '已完成' },
  cancelled: { type: 'info', text: '已取消' }
}

const getOrderStatusType = (status) => statusMap[status]?.type || ''
const getOrderStatusText = (status) => statusMap[status]?.text || status

// 列表数据
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')

// 统计数据
const statisticsData = ref([
  { title: '订单总数', value: 2345 },
  { title: '已完成', value: 1800 },
  { title: '待支付', value: 123 },
  { title: '本月新增', value: 210 }
]);

// 查询表单
const searchForm = reactive({
  orderId: '',
  username: '',
  phone: '',
  status: null
})

// 获取订单列表
const getOrderList = () => {
  loading.value = true
  setTimeout(() => {
    const filtered = searchQuery.value
      ? mockOrders.filter(o => 
          o.orderId.includes(searchQuery.value) || 
          o.username.includes(searchQuery.value)
        )
      : mockOrders
    
    total.value = filtered.length
    const start = (currentPage.value - 1) * pageSize.value
    orderList.value = filtered.slice(start, start + pageSize.value)
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getOrderList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderId = ''
  searchForm.username = ''
  searchForm.phone = ''
  searchForm.status = null
  currentPage.value = 1
  getOrderList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrderList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrderList()
}

// 订单详情
const showDetailDrawer = ref(false)
const currentOrder = ref(null)

// 获取订单进度
const getOrderProgress = (status) => {
  const statusMap = {
    'pending': 1,
    'paid': 2,
    'shipped': 3,
    'completed': 4,
    'cancelled': 1
  }
  return statusMap[status] || 1
}

// 查看订单详情
const handleViewDetail = (order) => {
  currentOrder.value = order
  showDetailDrawer.value = true
}

// 发货处理
const handleShip = async (order) => {
  try {
    await ElMessageBox.confirm(`确认发货订单：${order.orderId}？`)
    order.status = 'shipped'
    ElMessage.success('发货成功')
  } catch {
    // 取消发货
  }
}

// 初始化
getOrderList()
</script>

<style lang="scss" scoped>
.order-manager {
  padding: 20px;

  .statistics {
    margin-bottom: 20px;
    .stat-card {
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 8px;
      }
      .stat-title {
        color: #666;
      }
    }
  }

  .search-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .order-detail-drawer {
    padding: 20px;

    .progress-section {
      margin-bottom: 30px;
      padding: 20px;
      background: #f8f8f8;
      border-radius: 8px;
    }

    .detail-section {
      margin-bottom: 30px;
      
      .section-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        
        i {
          margin-right: 8px;
          color: #1890ff;
        }
      }

      .info-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;

        .info-item {
          .label {
            color: #666;
            margin-right: 8px;
          }
        }
      }

      .product-card {
        display: flex;
        padding: 15px;
        background: #f8f8f8;
        border-radius: 8px;

        img {
          width: 80px;
          height: 80px;
          object-fit: cover;
          border-radius: 4px;
          margin-right: 15px;
        }

        .product-info {
          h4 {
            margin: 0 0 10px;
          }

          .price {
            color: #ff4d4f;
            font-weight: bold;
          }
        }
      }

      .address-card {
        padding: 15px;
        background: #f8f8f8;
        border-radius: 8px;

        .contact {
          margin-bottom: 8px;

          .name {
            font-weight: bold;
            margin-right: 15px;
          }

          .phone {
            color: #666;
          }
        }

        .address {
          color: #333;
        }
      }

      .amount-list {
        .amount-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;

          .discount {
            color: #52c41a;
          }

          &.total {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #ddd;
            font-weight: bold;

            .total-amount {
              color: #ff4d4f;
              font-size: 18px;
            }
          }
        }
      }
    }

    .drawer-footer {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 20px;
      background: #fff;
      border-top: 1px solid #f0f0f0;
      text-align: right;

      .el-button {
        margin-left: 8px;
      }
    }
  }
}
</style>
